"""
数据导入脚本
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from dotenv import load_dotenv
load_dotenv()

from app import create_app
from app.extensions import db
from app.services.data_importer import DataImporter
from app.models.user import User, StudentProfile, TeacherProfile
import pandas as pd


def import_teachers(file_path='data/teachers.csv'):
    """导入教师数据"""
    print(f"\n导入教师数据: {file_path}")
    
    try:
        df = pd.read_csv(file_path)
        success_count = 0
        fail_count = 0
        
        for idx, row in df.iterrows():
            try:
                # 检查用户是否已存在
                existing = User.query.filter_by(username=row['username']).first()
                if existing:
                    print(f"  跳过: 用户名 '{row['username']}' 已存在")
                    fail_count += 1
                    continue
                
                # 创建教师用户
                user = User(
                    username=row['username'],
                    email=row['email'],
                    role='teacher',
                    first_name=row['first_name'],
                    last_name=row['last_name'],
                    phone=row.get('phone', '')
                )
                user.set_password(row.get('password', 'password123'))
                
                db.session.add(user)
                db.session.flush()
                
                # 创建教师profile
                profile = TeacherProfile(
                    user_id=user.id,
                    employee_id=row['employee_id'],
                    department=row.get('department', ''),
                    title=row.get('title', ''),
                    bio=row.get('bio', '')
                )
                
                db.session.add(profile)
                db.session.commit()
                success_count += 1
                
            except Exception as e:
                print(f"  错误 (行 {idx+2}): {str(e)}")
                db.session.rollback()
                fail_count += 1
                continue
        
        print(f"✓ 教师导入完成: 成功 {success_count}, 失败 {fail_count}")
        
    except Exception as e:
        print(f"✗ 文件读取错误: {str(e)}")


def import_all_data():
    """导入所有数据"""
    app = create_app('development')
    
    with app.app_context():
        print("=" * 60)
        print("开始导入演示数据")
        print("=" * 60)
        
        importer = DataImporter()
        
        # 1. 导入教师
        import_teachers('data/teachers.csv')
        
        # 2. 导入学生
        print("\n导入学生数据...")
        if importer.import_students('data/students.csv'):
            summary = importer.get_summary()
            print(f"✓ 学生导入完成: 成功 {summary['success_count']}, 失败 {summary['fail_count']}")
            if summary['errors']:
                print(f"  错误数: {len(summary['errors'])}")
        else:
            print(f"✗ 学生导入失败")
            summary = importer.get_summary()
            for error in summary['errors'][:5]:
                print(f"    - {error}")
        
        # 重置计数器
        importer = DataImporter()
        
        # 3. 导入课程
        print("\n导入课程数据...")
        if importer.import_courses('data/courses.csv'):
            summary = importer.get_summary()
            print(f"✓ 课程导入完成: 成功 {summary['success_count']}, 失败 {summary['fail_count']}")
        else:
            print(f"✗ 课程导入失败")
            summary = importer.get_summary()
            for error in summary['errors'][:5]:
                print(f"    - {error}")
        
        # 重置计数器
        importer = DataImporter()
        
        # 4. 导入成绩
        print("\n导入成绩数据 (这可能需要几分钟)...")
        if importer.import_grades('data/grades.csv'):
            summary = importer.get_summary()
            print(f"✓ 成绩导入完成: 成功 {summary['success_count']}, 失败 {summary['fail_count']}")
        else:
            print(f"✗ 成绩导入失败")
            summary = importer.get_summary()
            for error in summary['errors'][:5]:
                print(f"    - {error}")
        
        print("\n" + "=" * 60)
        print("数据导入完成！")
        print("=" * 60)
        
        # 统计信息
        print("\n数据库统计:")
        print(f"  - 用户总数: {User.query.count()}")
        print(f"  - 学生数: {User.query.filter_by(role='student').count()}")
        print(f"  - 教师数: {User.query.filter_by(role='teacher').count()}")
        print(f"  - 管理员数: {User.query.filter_by(role='admin').count()}")
        
        from app.models.course import Course
        from app.models.student_course import StudentCourse
        print(f"  - 课程数: {Course.query.count()}")
        print(f"  - 成绩记录数: {StudentCourse.query.count()}")


if __name__ == '__main__':
    import_all_data()










